package com.gzedu.ecloud.common.utils;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;


public class Hex {
	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	public static final String DEFAULT_CHARSET_NAME = "UTF-8";
	private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
			'e', 'f' };

	private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
			'E', 'F' };
	private final Charset charset;
	/**
	 * 用于计算62机制
	 */
	final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
			'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
			'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
			'X', 'Y', 'Z' };
	final static Map<Character, Integer> digitMap = new HashMap<Character, Integer>();
	static {
		for (int i = 0; i < digits.length; i++) {
			digitMap.put(digits[i], (int) i);
		}
	}
	/**
	 * 支持的最大进制数
	 */
	public static final int MAX_RADIX = digits.length;
	/**
	 * 支持的最小进制数
	 */
	public static final int MIN_RADIX = 2;

	/**
	 * 将长整型数值转换为指定的进制数（最大支持62进制，字母数字已经用尽）
	 * 
	 * @param i
	 * @param radix
	 * @return
	 */
	public static String toString(long i, int radix) {
		if (radix < MIN_RADIX || radix > MAX_RADIX)
			radix = 10;
		if (radix == 10)
			return Long.toString(i);

		final int size = 65;
		int charPos = 64;

		char[] buf = new char[size];
		boolean negative = (i < 0);

		if (!negative) {
			i = -i;
		}

		while (i <= -radix) {
			buf[charPos--] = digits[(int) (-(i % radix))];
			i = i / radix;
		}
		buf[charPos] = digits[(int) (-i)];

		if (negative) {
			buf[--charPos] = '-';
		}

		return new String(buf, charPos, (size - charPos));
	}

	/**
	 * 将字符串转换为长整型数字
	 * 
	 * @param s
	 *            数字字符串
	 * @param radix
	 *            进制数
	 * @return
	 */
	public static long toNumber(String s, int radix) {
		if (s == null) {
			throw new NumberFormatException("null");
		}

		if (radix < MIN_RADIX) {
			throw new NumberFormatException("radix " + radix + " less than Numbers.MIN_RADIX");
		}
		if (radix > MAX_RADIX) {
			throw new NumberFormatException("radix " + radix + " greater than Numbers.MAX_RADIX");
		}

		long result = 0;
		boolean negative = false;
		int i = 0, len = s.length();
		long limit = -Long.MAX_VALUE;
		long multmin;
		Integer digit;

		if (len > 0) {
			char firstChar = s.charAt(0);
			if (firstChar < '0') {
				if (firstChar == '-') {
					negative = true;
					limit = Long.MIN_VALUE;
				} else if (firstChar != '+')
					throw forInputString(s);

				if (len == 1) {
					throw forInputString(s);
				}
				i++;
			}
			multmin = limit / radix;
			while (i < len) {
				digit = digitMap.get(s.charAt(i++));
				if (digit == null) {
					throw forInputString(s);
				}
				if (digit < 0) {
					throw forInputString(s);
				}
				if (result < multmin) {
					throw forInputString(s);
				}
				result *= radix;
				if (result < limit + digit) {
					throw forInputString(s);
				}
				result -= digit;
			}
		} else {
			throw forInputString(s);
		}
		return negative ? result : -result;
	}

	static NumberFormatException forInputString(String s) {
		return new NumberFormatException("For input string: \"" + s + "\"");
	}

	public static byte[] decodeHex(char[] data) throws RuntimeException {
		int len = data.length;

		if ((len & 0x1) != 0) {
			throw new RuntimeException("Odd number of characters.");
		}

		byte[] out = new byte[len >> 1];

		int i = 0;
		for (int j = 0; j < len; ++i) {
			int f = toDigit(data[j], j) << 4;
			++j;
			f |= toDigit(data[j], j);
			++j;
			out[i] = (byte) (f & 0xFF);
		}

		return out;
	}

	public static char[] encodeHex(byte[] data) {
		return encodeHex(data, true);
	}

	public static char[] encodeHex(byte[] data, boolean toLowerCase) {
		return encodeHex(data, (toLowerCase) ? DIGITS_LOWER : DIGITS_UPPER);
	}

	protected static char[] encodeHex(byte[] data, char[] toDigits) {
		int l = data.length;
		char[] out = new char[l << 1];

		int i = 0;
		for (int j = 0; i < l; ++i) {
			out[(j++)] = toDigits[((0xF0 & data[i]) >>> 4)];
			out[(j++)] = toDigits[(0xF & data[i])];
		}
		return out;
	}

	public static String encodeHexString(byte[] data) {
		return new String(encodeHex(data));
	}

	protected static int toDigit(char ch, int index) throws RuntimeException {
		int digit = Character.digit(ch, 16);
		if (digit == -1) {
			throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index);
		}
		return digit;
	}

	public Hex() {
		this.charset = DEFAULT_CHARSET;
	}

	public Hex(Charset charset) {
		this.charset = charset;
	}

	public Hex(String charsetName) {
		this(Charset.forName(charsetName));
	}

	public byte[] decode(byte[] array) throws RuntimeException {
		return decodeHex(new String(array, getCharset()).toCharArray());
	}

	public Object decode(Object object) throws RuntimeException {
		try {
			char[] charArray = (object instanceof String) ? ((String) object).toCharArray() : (char[]) (char[]) object;
			return decodeHex(charArray);
		} catch (ClassCastException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public byte[] encode(byte[] array) {
		return encodeHexString(array).getBytes(getCharset());
	}

	public Object encode(Object object) throws RuntimeException {
		try {
			byte[] byteArray = (object instanceof String) ? ((String) object).getBytes(getCharset())
					: (byte[]) (byte[]) object;

			return encodeHex(byteArray);
		} catch (ClassCastException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public Charset getCharset() {
		return this.charset;
	}

	public String getCharsetName() {
		return this.charset.name();
	}

	public String toString() {
		return super.toString() + "[charsetName=" + this.charset + "]";
	}
}